
import React,{Fragment} from "react";
import {Button, Form, Table, Input, InputNumber,message} from "antd";
import FormInput from "../form/FormInput";
import {observer} from "mobx-react";
import FormUpload from "../form/FormUpload";
import FormShowPic from "../form/FormShowPic";
import FormMulInput from "../form/FormMulInput";
import FormSelect from "../form/FormSelect";
import FormMulSelect from "../form/FormMulSelect";
import FormTimePicker from "../form/FormTimePicker";
import FormDatePicker from "../form/FormDatePicker";
import FormMonthPicker from "../form/FormMonthPicker";
import FormYearPicker from "../form/FormYearPicker";
import FormRadio from "../form/FormRadio";
import FormCheckBox from "../form/FormCheckBox";
import FormPointPicker from "../form/FormPointPicker";
import FormPasswordInput from "../form/FormPasswordInput";
import FormTimeRangePicker from "../form/FormTimeRangePicker"
import FormDateRangePicker from "../form/FormDateRangePicker"
import FormMonthRangePicker from "../form/FormMonthRangePicker"
import FormYearRangePicker from "../form/FormYearRangePicker"
import FormTreeSelect from "../form/FormTreeSelect"
import FormText from "../form/FormText"
import FormCart from "../form/FormCart"
import FormSignName from "../form/FormSignName"
import {urlEncode} from "../../libs/funcs";
import store from "../../pages/generate/ordinary/Store";
import service from "../../libs/request";
import FormTablesStore from "../../stores/FormTablesStore"
import FormTitle from "../form/FormTitle";

const EditableContext = React.createContext();
const EditableRow = ({ form, index, ...props }) => (
    <EditableContext.Provider value={form}>
        <tr {...props} />
    </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
    constructor(props) {
        super(props);
    }

    state = {
        editing: false,
    };

    toggleEdit = () => {
        const editing = !this.state.editing;
        this.setState({ editing }, () => {
            if (editing) {
                this.input.focus();
            }
        });
    };

    save = e => {
        const { record, handleSave } = this.props;
        this.form.validateFields((error, values) => {
            if (error && error[e.currentTarget.id]) {
                return;
            }
            this.toggleEdit();
            handleSave({ ...record, ...values });
        });
    };

    renderCell = form => {
        this.form = form;
        const { children, dataIndex, record, title ,rules } = this.props;
        const { editing } = this.state;
        return editing ? (
            <Form.Item style={{ margin: 0 }}>
                {form.getFieldDecorator(`${dataIndex}`, {
                    rules : rules ? rules: [
                        {
                            required: true,
                            message: `${title} is required.`,
                        },
                    ],
                    initialValue: record[dataIndex],
                })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
            </Form.Item>
        ) : (
            <div
                className="editable-cell-value-wrap"
                style={{ paddingRight: 24 }}
                onClick={this.toggleEdit}
            >
                {children}
            </div>
        );
    };

    render() {
        const {
            editable,
            dataIndex,
            title,
            record,
            index,
            handleSave,
            children,
            ...restProps
        } = this.props;
        return (
            <td {...restProps}>
                {editable ? (
                    <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
                ) : (
                    children
                )}
            </td>
        );
    }
}

/**
 * 根据配置渲染的表单组件
 */
@observer
class ActionFormTable extends React.Component{
    constructor(props) {
        super(props);
        const {table_config} = props
        this.columns = table_config.tableColumns
        this.state = {
            dataSource: table_config.dataSource,
            count: 0,
        };
        FormTablesStore.setFrom(props.form);
    }

    handleSave = row => {
        const {table_config} = this.props;
        const url = table_config.tableSaveUri;
        const newData = [...this.state.dataSource];
        if(!row.hasOwnProperty("id")){
            message.error("缺少id字段，请联系开发");
        }
        const index = newData.findIndex(item => row.id === item.id);
        const item = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row,
        });
        this.setState({ dataSource: newData });
        FormTablesStore.summitData(url,{data:JSON.stringify(row)});
        // service.request({
        //     url:url,
        //     method:"post",
        //     data: {data:JSON.stringify(row)}
        // }).then(response => {
        //     if (response.data.code === 200){
        //         console.log(response.data)
        //     }
        //
        // })
    };

    render() {
        const components = {
            body: {
                row: EditableFormRow,
                cell: EditableCell,
            },
        };
        const {config, table_config} = this.props;

        const { dataSource }= this.state
        const columns = this.columns.map(col => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    key: col.key,
                    title: col.title,
                    rules:col.rules,
                    handleSave: this.handleSave,
                }),
            };
        });
        const title = table_config.title;
        return (
            <Fragment>
                <Form labelCol={{span: 6}} wrapperCol={{span: 14}}>
                    {
                        title ? <FormTitle label={title}/> :""
                    }

                    {config.map((item,index) => {
                        if (item["component"] === "FormUpload"){
                            console.log(item["single"],"--------------------")
                            return <FormUpload key={index} form={this.props.form} field={item["field"]}  label={item["label"]} single={item["single"]} fileType={item["fileType"]} initialValue={item["initialValue"]} rules={item["rules"]}  disabled={item["disabled"]}/>
                        }if (item["component"] === "FormShowPic"){
                            return <FormShowPic key={index} form={this.props.form} field={item["field"]}  label={item["label"]} single={item["single"]} fileType={item["fileType"]} initialValue={item["initialValue"]} rules={item["rules"]}  disabled={item["disabled"]}/>
                        }else if (item["component"] === "FormInput"){
                            return <FormInput key={index} form={this.props.form} label={item["label"]} field={item["field"]} allowClear={item["allowClear"]} placeholder={item["placeholder"]} initialValue={item["initialValue"]} rules={item["rules"]}  disabled={item["disabled"]} addonAfter={item["addonAfter"]} addonBefore={item["addonBefore"]}/>
                        }else if (item["component"] === "FormMulInput"){
                            return <FormMulInput key={index} form={this.props.form} label={item["label"]} field={item["field"]}  placeholder={item["placeholder"]} rows={item["rows"]} allowClear={item["allowClear"]} initialValue={item["initialValue"]} rules={item["rules"]} disabled={item["disabled"]}/>
                        }else if (item["component"] === "FormSelect"){
                            return <FormSelect key={index} form={this.props.form} label={item["label"]} field={item["field"]} options={item["options"]} allowClear={item["allowClear"]} showSearch={item["showSearch"]} placeholder={item["placeholder"]} initialValue={item["initialValue"]} rules={item["rules"]}  disabled={item["disabled"]}/>
                        }else if (item["component"] === "FormMulSelect"){
                            return <FormMulSelect key={index} form={this.props.form} label={item["label"]} field={item["field"]} options={item["options"]} showSearch={item["showSearch"]} placeholder={item["placeholder"]} allowClear={item["allowClear"]} initialValue={item["initialValue"]} rules={item["rules"]} disabled={item["disabled"]} />
                        }else if (item["component"] === "FormTimePicker"){
                            return <FormTimePicker key={index} form={this.props.form}  label={item["label"]} field={item["field"]} disabled={item["disabled"]} placeholder={item["placeholder"]} initialValue={item["initialValue"]} rules={item["rules"]}/>
                        }else if (item["component"] === "FormDatePicker"){
                            return <FormDatePicker key={index} form={this.props.form} label={item["label"]} field={item["field"]} disabled={item["disabled"]} placeholder={item["placeholder"]} initialValue={item["initialValue"]} rules={item["rules"]}/>
                        }else if (item["component"] === "FormMonthPicker"){
                            return <FormMonthPicker key={index} form={this.props.form} label={item["label"]} field={item["field"]} disabled={item["disabled"]} placeholder={item["placeholder"]} initialValue={item["initialValue"]} rules={item["rules"]}/>
                        }else if (item["component"] === "FormYearPicker"){
                            return <FormYearPicker key={index} form={this.props.form} label={item["label"]} field={item["field"]} disabled={item["disabled"]} placeholder={item["placeholder"]} initialValue={item["initialValue"]} rules={item["rules"]} />
                        }else if (item["component"] === "FormRadio"){
                            return <FormRadio key={index} form={this.props.form} label={item["label"]} field={item["field"]} options={item["options"]} initialValue={item["initialValue"]} rules={item["rules"]}  disabled={item["disabled"]}/>
                        }else if (item["component"] === "FormCheckBox"){
                            return <FormCheckBox key={index} form={this.props.form} label={item["label"]} field={item["field"]} options={item["options"]} initialValue={item["initialValue"]} rules={item["rules"]}  disabled={item["disabled"]}/>
                        }else if (item["component"] === "FormPointPicker"){
                            return <FormPointPicker key={index} form={this.props.form} placeholder={item["placeholder"]} field={item["field"]} initialValue={item["initialValue"]} rules={item["rules"]}  disabled={item["disabled"]}/>
                        }else if (item["component"] === "FormPasswordInput"){
                            return <FormPasswordInput key={index} form={this.props.form} label={item["label"]} field={item["field"]} allowClear={item["allowClear"]} placeholder={item["placeholder"]} initialValue={item["initialValue"]} rules={item["rules"]} disabled={item["disabled"]}/>
                        }else if (item["component"] === "FormTimeRangePicker"){
                            return <FormTimeRangePicker key={index} form={this.props.form} label={item["label"]} disabled={item["disabled"]} field={item["field"]} allowClear={item["allowClear"]} placeholder={item["placeholder"]} start={item["start"]} end={item["end"]} rules={item["rules"]}/>
                        }else if (item["component"] === "FormDateRangePicker"){
                            return <FormDateRangePicker key={index} form={this.props.form} label={item["label"]} disabled={item["disabled"]} field={item["field"]} allowClear={item["allowClear"]} placeholder={item["placeholder"]} start={item["start"]} end={item["end"]} rules={item["rules"]}/>
                        }else if (item["component"] === "FormMonthRangePicker"){
                            return <FormMonthRangePicker key={index} form={this.props.form} label={item["label"]} disabled={item["disabled"]} field={item["field"]} allowClear={item["allowClear"]} placeholder={item["placeholder"]} start={item["start"]} end={item["end"]} rules={item["rules"]}/>
                        }else if (item["component"] === "FormYearRangePicker"){
                            return <FormYearRangePicker key={index} form={this.props.form} label={item["label"]} disabled={item["disabled"]} field={item["field"]} allowClear={item["allowClear"]} placeholder={item["placeholder"]} start={item["start"]} end={item["end"]} rules={item["rules"]}/>
                        }else if(item["component"] === "FormTreeSelect"){
                            return <FormTreeSelect key={index} form={this.props.form} label={item["label"]} multiple={item["multiple"]} treeCheckable={item["treeCheckable"]}  treeData={item["options"]}  initialValue={item["initialValue"]} disabled={item["disabled"]} field={item["field"]} allowClear={item["allowClear"]} placeholder={item["placeholder"]} rules={item["rules"]} showLeafOnly={item["showLeafOnly"]} ext_config={item["ext_config"]}/>
                        }else if (item["component"] === "FormText"){
                            return <FormText options={item["options"]} key={index} form={this.props.form} label={item["label"]} field={item["field"]} allowClear={item["allowClear"]} placeholder={item["placeholder"]} initialValue={item["initialValue"]} rules={item["rules"]}  disabled={item["disabled"]} addonAfter={item["addonAfter"]} addonBefore={item["addonBefore"]}/>
                        }else if (item["component"] === "BUTTON"){
                            return <div key={index} style={{width:528,margin:"0 auto"}}><Button href={this.state.href} icon={item["icon"]} size={item["size"]} target={item["target"]} type={item["type"]} block={item["block"]} onClick={(e) => {this.handleButtonClick(item["href"],item["name"]);return false;}}>{item["label"]}</Button></div>
                        }else if (item["component"] === "FormCart"){
                            return <FormCart key={index} form={this.props.form} label={item["label"]} field={item["field"]} allowClear={item["allowClear"]} placeholder={item["placeholder"]} initialValue={item["initialValue"]} rules={item["rules"]}  disabled={item["disabled"]}  addonAfter={item["addonAfter"]} />
                        }else if (item["component"] === "FormSignName"){
                            return <FormSignName key={index} form={this.props.form} label={item["label"]} field={item["field"]} allowClear={item["allowClear"]} placeholder={item["placeholder"]} initialValue={item["initialValue"]} rules={item["rules"]}  disabled={item["disabled"]}/>
                        }else {
                            return <FormInput key={index} form={this.props.form} label={item["label"]} field={item["field"]} allowClear={item["allowClear"]} placeholder={item["placeholder"]} initialValue={item["initialValue"]} rules={item["rules"]} disabled={item["disabled"]}/>
                        }
                    })}
                </Form>
                <EditableContext.Provider value={this.props.form}>
                    <Table
                        components={components}
                        dataSource={dataSource}
                        columns={columns}
                        rowClassName={() => 'editable-row'}
                        bordered
                        pagination={false}
                    />
                </EditableContext.Provider>
            </Fragment>

        )
    }
}
export default ActionFormTable

